package de.fhkoeln.avs.parallelbreadthfirstsearch.infinitegraph;

import java.util.HashMap;
import java.util.Iterator;

import com.infinitegraph.ConfigurationException;
import com.infinitegraph.GraphDatabase;
import com.infinitegraph.StorageException;
import com.infinitegraph.Transaction;
import com.infinitegraph.Vertex;
import de.fhkoeln.avs.graphbuild.infinitegraph.storage.AvsVertex;
import de.fhkoeln.avs.parallelbreadthfirstsearch.infinitegraph.mockup.RAMPersistentVertex;

public class CacheBuilder {

    public static AvsVertex cacheGraphAndReturnStart(String startTerm) throws StorageException, ConfigurationException {
        //TODO: Wenn Zeit dann refactorn
        HashMap<String, AvsVertex> cached = new HashMap<String, AvsVertex>();
        GraphDatabase graph = DatabaseConnection.getConnection();
        Transaction tx = graph.beginTransaction();
        Iterator<Vertex> verticesOfGraph = graph.getVertices().iterator();
        while (verticesOfGraph.hasNext()) {
            AvsVertex vertex = (AvsVertex) verticesOfGraph.next();
            RAMPersistentVertex cachedVertex = (RAMPersistentVertex) cached.get(vertex.getName());
            if (cachedVertex == null) {
                cachedVertex = new RAMPersistentVertex();
                cachedVertex.setName(vertex.getName());
                cachedVertex.setOwner(vertex.getOwner());
                cached.put(cachedVertex.getName(), cachedVertex);
            }
            for (AvsVertex child : vertex.getChilds()) {
                RAMPersistentVertex childCachedVertex = (RAMPersistentVertex) cached.get(child.getName());
                if (childCachedVertex == null) {
                    childCachedVertex = new RAMPersistentVertex();
                    childCachedVertex.setName(child.getName());
                    childCachedVertex.setOwner(child.getOwner());
                    cached.put(childCachedVertex.getName(), childCachedVertex);
                }
                cachedVertex.addChild(childCachedVertex);
            }
        }
        tx.commit();
        return cached.get(startTerm);
    }
}
